package com.example.aihub.service.impl;

import com.example.aihub.entity.Post;
import com.example.aihub.entity.PostCategory;
import com.example.aihub.entity.PostLike;
import com.example.aihub.entity.User;
import com.example.aihub.exception.ResourceNotFoundException;
import com.example.aihub.repository.PostRepository;
import com.example.aihub.repository.PostLikeRepository;
import com.example.aihub.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class PostServiceImpl implements PostService {

    private final PostRepository postRepository;
    private final PostLikeRepository postLikeRepository; // 添加这个

    @Autowired
    public PostServiceImpl(PostRepository postRepository, PostLikeRepository postLikeRepository) { // 修改构造函数
        this.postRepository = postRepository;
        this.postLikeRepository = postLikeRepository;
    }

    @Override
    public Post createPost(Post post) {
        return postRepository.save(post);
    }

    @Override
    public Optional<Post> getPostById(Long id) {
        return postRepository.findById(id);
    }

    @Override
    public Post updatePost(Post post) {
        if (postRepository.existsById(post.getId())) {
            return postRepository.save(post);
        }
        throw new ResourceNotFoundException("帖子不存在: " + post.getId());
    }

    @Override
    public void deletePost(Long id) {
        if (postRepository.existsById(id)) {
            postRepository.deleteById(id);
        } else {
            throw new ResourceNotFoundException("帖子不存在: " + id);
        }
    }

    @Override
    public Post incrementViewCount(Long id) {
        Post post = postRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("帖子不存在: " + id));
        post.setViewCount(post.getViewCount() + 1);
        return postRepository.save(post);
    }

    @Override
    public Post likePost(Long id, User user) {
        Post post = postRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("帖子不存在: " + id));
        
        // 检查用户是否已经点过赞
        if (postLikeRepository.existsByUserAndPost(user, post)) {
            // 用户已经点赞，可以选择取消点赞或抛出异常
            throw new RuntimeException("您已经点赞过此帖子");
        }
        
        // 创建点赞记录
        PostLike postLike = new PostLike(user, post);
        postLikeRepository.save(postLike);
        
        // 更新点赞数
        post.setLikeCount(post.getLikeCount() + 1);
        return postRepository.save(post);
    }

    @Override
    public List<Post> getPostsByUser(User user) {
        return postRepository.findByUser(user);
    }

    @Override
    public List<Post> getLatestPosts(int limit) {
        return postRepository.findTop10ByStatusOrderByCreatedAtDesc(Post.PostStatus.PUBLISHED);
    }

    @Override
    public List<Post> searchPosts(String keyword) {
        return postRepository.findByTitleContainingIgnoreCase(keyword);
    }

    @Override
    public List<Post> getAllPosts(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Post> postPage = postRepository.findAll(pageable);
        return postPage.getContent();
    }

    @Override
    public List<Post> getHotPosts(int limit) {
        return postRepository.findTop5ByStatusOrderByLikeCountDesc(Post.PostStatus.PUBLISHED);
    }

    @Override
    public List<Post> getPostsByCategory(PostCategory category) {
        // 获取特定分类下的所有帖子
        return postRepository.findByCategory(category);
    }

    @Override
    public List<Post> getPublishedPostsByCategory(PostCategory category, int page, int size) {
        // 创建分页请求对象
        Pageable pageable = PageRequest.of(page, size);
        // 获取特定分类下的已发布帖子，并按创建时间倒序排序
        List<Post> posts = postRepository.findByCategoryAndStatusOrderByCreatedAtDesc(category, Post.PostStatus.PUBLISHED);
        
        // 实现手动分页
        int start = Math.min(page * size, posts.size());
        int end = Math.min(start + size, posts.size());
        
        return posts.subList(start, end);
    }
}